package com.example.exam;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    String token;
    String username;
    String password;
    EditText user;
    EditText pass;
    String URL;
    Boolean key, key2;
    Thread t;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();//隐藏标题栏
        setContentView(R.layout.activity_login);
        username = null;
        password = null;
        key = false;
        key2 = false;
        token = "23";
        Button button = (Button) findViewById(R.id.btn_login);
        user = (EditText) findViewById(R.id.et_user);
        pass = (EditText) findViewById(R.id.et_paw);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                URL = "http://exam.mujiayiling.com/api/userlogin?username=";
                username = user.getText().toString();
                password = pass.getText().toString();
                URL += username + "&password=" + password;
                sendRequestWithOkHttp();
                for(int i = 0; i < 999999999; i++) {//这里要等一下服务器那边的线程
                    //Log.d("asda23", key+"");
                    if(key) break;
                }
                for(int i = 0; i < 999999999 && key == false; i++);
                    //Log.d("asda25", key+"");
                if(key == false) Toast.makeText(LoginActivity.this, "链接服务器失败", Toast.LENGTH_SHORT).show();
                while(!key2);
                if(token.equals("23")) {
                    key2 = false;
                    key = false;
                    Log.d("asda23", token);
                    Toast.makeText(LoginActivity.this, "账号或密码错误", Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.d("aaas", URL);
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("token_data", token);
                startActivity(intent);
                Log.d("asda2", token);
                save(token);
                finish();
            }
        });
    }

    private void sendRequestWithOkHttp(){
        //开启新线程做耗时操作
        new Thread(new Runnable(){
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(URL)
                            .build();//创建一个Request对象
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                    Log.d("asda", URL);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    void parseJSONWithJSONObject(String jsonData){
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            String MessageJSON = jsonObject.getString("message");
            key = true;
            if(MessageJSON.equals("登陆成功!")) {
                JSONObject dataJSON = jsonObject.getJSONObject("data");
                token = dataJSON.getString("token");
                key2 = true;
                Log.d("asda1", token);
            }
            else{
                key2 = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public void save(String inputText){
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput("token", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

}
